/**
 * Created by yhg97p on 2016/9/26.
 */
'use strict';

define(['app'],function(app){
    //Service比较特殊，加载后还需要手动注入控制器
    app.register.service('booksService', function(){
        this.books = [
            {
                id: 0,
                name: 'javascript权威指南'
            },
            {
                id: 1,
                name: 'javascript高级程序设计'
            }
        ];
    });
    app.register.service('fileReader', ["$q", "$log", function($q, $log){
        var onLoad = function(reader, deferred, scope) {
            return function () {
                scope.$apply(function () {
                    deferred.resolve(reader.result);
                });
            };
        };

        var onError = function (reader, deferred, scope) {
            return function () {
                scope.$apply(function () {
                    deferred.reject(reader.result);
                });
            };
        };

        var getReader = function(deferred, scope) {
            var reader = new FileReader();
            reader.onload = onLoad(reader, deferred, scope);
            reader.onerror = onError(reader, deferred, scope);
            return reader;
        };

        var readAsDataURL = function (file, scope) {
            var deferred = $q.defer();
            var reader = getReader(deferred, scope);
            reader.readAsDataURL(file);
            return deferred.promise;
        };

        return {
            readAsDataUrl: readAsDataURL
        };
    }]);
    app.register.service('$prompt', function($compile, $rootScope, $q) {
        return {
            create: function(obj) { //创建弹窗
                this.pop = document.getElementById(obj.id);
                var string = '',
                    icon = obj.icon || 'icon-error',
                    text = obj.text || '',
                    backg = obj.backg || '';

                // var innerhtml = '<div class="prompt-pop ' + backg + '" id="poperDrap"><img width="12px" height="12px" src=' + src + ' /><span>' + text + '</span></div>';

                var innerhtml = '<div class="operation-tips-wrap" id="poperDrap"> ' +
                    '<div class="operation-tips ' + backg + '">' +
                    '<span>' +
                    '<i class="' + icon + '"></i>' + text +
                    '</span>' +
                    '</div>' +
                    '</div>';
                this.innerhtml = $compile(innerhtml)(obj.scope);
                angular.element(this.pop).append(this.innerhtml)

            },
            show: function(obj) { //显示弹窗
                if (this.popDiv) {
                    this.remove();
                    this.popDiv = null;
                    this.pop = null;
                    this.innerhtml = null;
                    clearTimeout(this.time);
                    this.callback = null;
                }
                this.callback = obj.callback;
                this.create(obj);
                this.popDiv = angular.element(document.getElementById('poperDrap'));
                this.popDiv.addClass('current');

                var that = this;

                this.time = setTimeout(function() {
                    that.hide();
                }, 2000);
            },
            hide: function() { //隐藏弹窗
                var deferred = $q.defer();
                if (this.popDiv) {
                    // this.popDiv.removeClass('current');
                    this.popDiv.addClass('figerout');

                    var _this = this;
                    setTimeout(function() {
                        _this.remove();
                        _this.popDiv = null;
                        _this.pop = null;
                        _this.innerhtml = null;
                        _this.callback && (_this.callback)();
                        _this.callback = null;
                        deferred.resolve('11');
                    }, 1000);

                    return deferred.promise;
                }

            },
            remove: function() { //移除弹窗
                try {
                    this.pop.removeChild(document.getElementById('poperDrap'));
                } catch (e) {

                }
            },
            timeout: function($scope, res, callback) { //事件弹窗
                var that = this;
                var d = res;
                if (!d.data) {
                    res.data = d;
                }
                if (res.data.code == 1) {
                    this.show({
                        id: 'containers',
                        text: res.data.message,
                        icon: 'icon-success',
                        // src: 'images/icon-success.png',
                        backg: 'success',
                        callback: callback || null,
                        scope: $scope
                    });
                } else if (res.data.code == '-103') {
                    window.location.href = 'login.html';
                } else {
                    this.show({
                        id: 'containers',
                        text: res.data.message,
                        icon: 'icon-error',
                        // src: 'images/punish_failed.png',
                        backg: 'tips-orange',
                        callback: callback || null,
                        scope: $scope
                    });
                }
            }
        }
    });
    app.register.service('$confirm', function($compile, $rootScope, $q) {
        return {
            create: function(obj) { //创建弹窗
                this.pop = document.getElementById(obj.id);
                var len = obj.buttons.length,
                    second = false,
                    string = '',
                    title = obj.title || '',
                    text = obj.text || '',
                    remarks = obj.remarks || '';

                if (len == 2)
                    string = '<button id="buttons2">' + obj.buttons[1].text + '</button>';
                // var innerhtml = '<div class="bomb-box" id="bombConfirm">' +
                //     '<div class="bomb-bg"></div>' +
                //     '<div class="bomb-content">' +
                //     '<div class="bomb-box-header">' +
                //     '<span>' + title + '</span>' +
                //     '<img style="cursor: pointer;" id="bombCloseBtn" class="bomb-close" src="images/btn_close.png" >' +
                //     '</div>' +
                //     '<div class="bomb-box-content clearfix">' +
                //     '<div style="width: 15%;float: left;height: 120px;line-height: 120px;">' +
                //     '<i  style="background-image: url(\'images/prompt_tip_icon.png\');background-size: 100% 100%;width: 30px;height: 34px;display: inline-block;vertical-align: -16px;"></i>' +
                //     '</div>' +
                //     '<div style="width: 79%;float: left;height: 120px;text-align: left;padding: 25px 0;">' +
                //     '<div style="height: 40px;line-height: 20px;font-size: 18px;">' + text + '</div>' +
                //     '<div style="color: #666666;">' + remarks + '</div>' +
                //     '</div>' +
                //     '</div>' +
                //     '<div class="bomb-box-footer">' +
                //     '<button class="btn mian-btn" id="confirmButtons1" >' + obj.buttons[0].text + '</button>' +
                //     '<button class="btn" id="confirmButtons2" style="margin-left: 15px;" >' + obj.buttons[1].text + '</button>' +
                //     '</div>';


                var innerhtml = '<div style="display: block;" id="bombConfirm" class="modal fade in" tabindex="-1" role="dialog" aria-labelledby="bombConfirmLabel" aria-hidden="false">' +
                    '<div class="modal-backdrop fade in"></div>' +
                    '<div class="modal-dialog modal-sm">' +
                    '<div class="modal-content">' +
                    '<div class="modal-header">' +
                    '<div class="btn-close" data-dismiss="modal"><i class="icon-cuo" id="bombCloseBtn"></i></div>' +
                    '<h4 class="modal-title" >' + title + '</h4>' +
                    '</div>' +
                    '<div class="modal-body">' +
                    '<div class="confirm-cont">' +
                    '<i class="icon-prompt"></i>' +
                    '<div class="confirm-text">' +
                    '<h3>'+text+'</h3>' + remarks +
                    '</div>' +
                    '</div>' +
                    '</div>' +
                    '<div class="modal-footer">' +
                    '<button type="button" class="test-btn" id="confirmButtons1">' + obj.buttons[0].text + '</button>' +
                    (len == 2 ? '<button type="button" class="test-btn test-btn-gray" data-dismiss="modal" id="confirmButtons2">' + obj.buttons[1].text + '</button>' : '' ) +
                    '</div>' +
                    '</div>' +
                    '</div>' +
                    '</div>';

                // var innerhtml = '<div class="modal fade in" tabindex="-1" id="bombConfirm" role="dialog" aria-labelledby="bombConfirmLabel" aria-hidden="false" style="display: block;">' +
                //                 '  <div class="modal-backdrop fade in"></div>' +
                //                 '  <div class="modal-dialog modal-sm" style="margin-top: -230px;">'
                //                 '    <div class="modal-content">' +
                //                 '      <div class="modal-header">' +
                //                 '        <div class="btn-close" data-dismiss="modal"><i class="icon-close"></i></div>' +
                //                 '        <h4 class="modal-title" id="bombConfirmLabel">添加讲师</h4>' +
                //                 '      </div>' +
                //                 '      <div class="modal-body">' +
                //                 '        <div class="form-wrap add-training-form">' +
                //                 '123' +
                //                 '        </div>' +
                //                 '      </div>' +
                //                 '      <div class="modal-footer">' +
                //                 '        <button type="button" class="btn btn-blue">确定</button> ' +
                //                 '        <button type="button" class="btn btn-gray" data-dismiss="modal">取消</button>' +
                //                 '      </div>' +
                //                 '    <div>' +
                //                 '  <div>' +
                //                 '  <div>';

                this.innerhtml = $compile(innerhtml)(obj.scope);
                angular.element(this.pop).append(this.innerhtml)

                var that = this;
                setTimeout(function() { //事件监听 兼容IE8
                    var button1 = document.getElementById('confirmButtons1')
                    if (button1.addEventListener)
                        button1.addEventListener('click', obj.buttons[0].ontap);
                    else
                        button1.attachEvent('onclick', obj.buttons[0].ontap);

                    var closeButton = document.getElementById('bombCloseBtn')
                    if (button1.addEventListener)
                        closeButton.addEventListener('click', function() {
                            that.hide();
                        });
                    else
                        closeButton.attachEvent('onclick', function() {
                            that.hide();
                        });

                    if (len == 2) {
                        var button2 = document.getElementById('confirmButtons2');
                        if (button2.addEventListener) {
                            if (obj.buttons[1].ontap)
                                button2.addEventListener('click', obj.buttons[1].ontap);
                            else
                                button2.addEventListener('click', function() {
                                    that.hide();
                                });
                        } else {
                            if (obj.buttons[1].ontap)
                                button2.attachEvent('onclick', obj.buttons[1].ontap);
                            else
                                button2.attachEvent('onclick', function() {
                                    that.hide();
                                });
                        }
                    }
                });
            },
            show: function(obj) { //显示弹窗
                if (this.popDiv) {
                    this.popDiv = null;
                    this.remove();
                    this.pop = null;
                    this.innerhtml = null;
                }
                this.create(obj);
                this.bombConfirm = angular.element(document.getElementById('bombConfirm'));
                this.popDiv = angular.element(document.getElementById('popDiv'));
                this.popDiv.addClass('animation-pop');
            },
            hide: function() { //隐藏弹窗
                this.bombConfirm.remove();
                var deferred = $q.defer();
                this.popDiv.removeClass('animation-pop');
                this.popDiv.addClass('animation-popout');

                var _this = this;
                setTimeout(function() {
                    _this.popDiv = null;
                    _this.remove();
                    _this.pop = null;
                    _this.innerhtml = null;
                    deferred.resolve('11');
                }, 500);

                return deferred.promise;
            },
            remove: function() { //移除弹窗
                try {
                    this.pop.removeChild(document.getElementById('poperDrap'));
                } catch (e) {

                }
            },
            timeout: function($scope, res) { //事件弹窗
                var that = this;
                if (res.data.code == 500) {
                    this.show({
                        id: 'uiViews',
                        title: '异常',
                        text: res.data.message,
                        buttons: [{
                            text: '确定',
                            ontap: function() {
                                that.hide();
                            }
                        }],
                        scope: $scope
                    });
                } else if (res.data.code == 603) {
                    this.show({
                        id: 'uiViews',
                        title: '提示',
                        text: res.data.message,
                        buttons: [{
                            text: '确定',
                            ontap: function() {
                                window.location = 'login.html';
                            }
                        }],
                        scope: $scope
                    });
                } else
                    this.show({
                        id: 'uiViews',
                        title: '提示',
                        text: res.data.message,
                        buttons: [{
                            text: '确定',
                            ontap: function() {
                                that.hide();
                            }
                        }],
                        scope: $scope
                    });
            },
            warning: function($scope, title, message) {
                var that = this;
                this.show({
                    id: 'uiViews',
                    title: title,
                    text: message,
                    buttons: [{
                        text: '确定',
                        ontap: function() {
                            that.hide();
                        }
                    }],
                    scope: $scope
                });
            }
        }
    });
    app.register.service('$Ajax', function ($http, $prompt) {
        return {
            post: function (url, data) { //method：post

                var promise = $http({
                    method: 'post',
                    url: url,
                    // headers: {
                    //   'Content-Type': 'application/x-www-form-urlencoded'
                    // },
                    withCredentials: true,
                    data: data,
                });
                return promise;
            },
            postData: function (url, data, $scope) { //method：post

                var promise = $http({
                    method: 'post',
                    url: url,
                    withCredentials: true,
                    timeout: 300000,
                    data: data
                })
                    .success(function (response, status, headers, config) {

                    })
                    .error(function (response, status, headers, config) {
                        $prompt.timeout($scope, {
                            data: {
                                code: 404,
                                message: '网络异常，请稍后再试'
                            }
                        });
                    });
                return promise;
            },
            postJson: function (url, data, $scope) { //method：post

                var promise = $http({
                    method: 'post',
                    url: url,
                    withCredentials: true,
                    timeout: 300000,
                    data: data,
                    headers: {'Content-Type': 'application/json;charset=UTF-8'}
                })
                    .success(function (response, status, headers, config) {

                    })
                    .error(function (response, status, headers, config) {
                        $prompt.timeout($scope, {
                            data: {
                                code: 404,
                                message: '网络异常，请稍后再试'
                            }
                        });
                    });
                return promise;
            },
            get: function (url) { //method：get

                var promise = $http({
                    method: 'GET',
                    url: url,
                    withCredentials: true,
                    params: {
                        times: new Date().getTime()
                    }
                });
                return promise;
            },
            getlist: function (url, $scope) { //method：get

                var promise = $http({
                    url: url,
                    withCredentials: true,
                    timeout: 300000,
                    method: 'GET',
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                    params: {
                        times: new Date().getTime()
                    }
                })
                    .success(function (response, status, headers, config) {
                        $scope.isAjaxError = false;
                        $scope.pageListLoading = false;
                    })
                    .error(function (response, status, headers, config) {
                        $scope.list = null;
                        $scope.isAjaxError = true;
                        $scope.pageListLoading = false;
                        $prompt.timeout($scope, {
                            data: {
                                code: 404,
                                message: '网络异常，请稍后再试'
                            }
                        });
                    });
                return promise;
            },
            putData: function (url, data, $scope) { //put
                var promise = $http({
                    method: 'PUT',
                    url: url,
                    timeout: 300000,
                    data: data
                })
                    .success(function (response, status, headers, config) {

                    })
                    .error(function (response, status, headers, config) {
                        $prompt.timeout($scope, {
                            data: {
                                code: 404,
                                message: '网络异常，请稍后再试'
                            }
                        });
                    });
                return promise;
            },
            fileUpload: function (url, data, $scope) {
                var promise = $http({
                    method: 'POST',
                    url: url,
                    timeout: 300000,
                    data: data,
                    headers: {
                        'Content-Type': undefined
                    },
                    transformRequest: function (data) {
                        var formData = new FormData();
                        for (var a in data) {
                            formData.append(a, data[a])
                        }
                        return formData;
                    }
                })
                    .success(function (response, status, headers, config) {

                    })
                    .error(function (response, status, headers, config) {
                        $prompt.timeout($scope, {
                            data: {
                                code: 404,
                                message: '网络异常，请稍后再试'
                            }
                        });
                    });
                return promise;
            },
            put: function (url, data) { //put
                var promise = $http({
                    method: 'PUT',
                    url: url,
                    data: data
                });
                return promise;
            },
            delete: function (url) { //delete
                var promise = $http({
                    method: 'DELETE',
                    url: url
                });
                return promise;
            }
        };
    });
    app.register.directive('pageLink', function ($Ajax) {
        return {
            restrict: 'EAMC',
            replace: false,
            transclude: true,
            scope: {
                conf: '=conf'
            },
            template: '<div id="pageing" class="paging clearfix">' +
            '<div class="page-prev"><span ><a class="btn-page first-page" ng-class="{\'btn-disabled\':dataPageNo==1}" href="javascript:void(0)" ng-click="dataPageNo!==1&&changePage($event,1)"></a></span>' +
            '<span ><a class="btn-page previous-page" href="javascript:void(0)" ng-class="{\'btn-disabled\':dataPageNo==1}"  ng-click="dataPageNo!==1&&changePage($event,dataPageNo-1)"></a></span></div>' +
            '<ul><li ng-repeat="pageNumber in pageNumberList" ng-class="{ \'active\':  pageNumber === dataPageNo }"><a class="btn-page" ng-click="changePage($event,pageNumber)" ng-bind="pageNumber"></a></li></ul>' +
            '<div class="page-next"><span><a class="btn-page next-page" href="javascript:void(0)" ng-class="{\'btn-disabled\':dataPageNo==dataPageCount}"  ng-click="dataPageNo!==dataPageCount&&changePage($event,dataPageNo+1)"></a></span>' +
            '<span><a class="btn-page last-page" href="javascript:void(0)" ng-class="{\'btn-disabled\':dataPageNo==dataPageCount}" ng-click="dataPageNo!==dataPageCount&&changePage($event, dataPageCount)"></a></span></div>' +
            '</div>',
            link: function (scope, element,$scope) {
                scope.dataUrl = scope.conf.url;
                scope.dataStartPage = scope.conf.currentPage || 1;
                scope.dataPageNo = scope.currentPage || 1;
                scope.pageNumberListLength = 5;
                //总页数
                scope.dataPageCount = 0;
                scope.pageNumberList = [];
                scope.dataPer = scope.page_size || 10;
                var pageing=document.getElementById('pageing')
                //改变页码
                scope.changePage = function (e, page, p) {
                    var flag=angular.isNumber(page);
                    // scope.pageData = 'page_size=' + scope.dataPer + '&page_no=' + page;
                    // scope.pageData = 'page_no=' + page;
                    scope.pageData = {
                        page_no:page,
                        cate_ids:scope.conf.cate_ids,
                        check_levels:scope.conf.check_levels,
                        real_name:scope.conf.real_name
                    };
                    $Ajax.postData(scope.dataUrl,scope.pageData).then(function(res){
                        scope.conf.loading_show = true;
                        if(res.data.success){
                            scope.conf.loading_show = false;
                            var oHeight=document.documentElement.scrollTop||document.body.scrollTop;
                            if(oHeight!=0){
                                window.scrollTo(0,0)
                            }
                            if(res.data.data.length) {
                                res = res.data;
                                scope.conf.isKong=false;
                                scope.conf.returnValue = res.data;
                                scope.dataPageCount = res.page.page_total;
                                if (flag) {
                                    scope.dataPageNo = res.page.page_current;
                                }
                                scope.conf.isShow = true;
                                // 总页数为0时
                                if (scope.dataPageCount === 0) {
                                    scope.pageNumberList = [];
                                    // 总页数小于等于最大显示页数时
                                } else if (scope.dataPageCount <= scope.pageNumberListLength) {
                                    scope.pageNumberList = [];
                                    for (var i = 0; i < scope.dataPageCount; i++) {
                                        scope.pageNumberList.push(i + 1)
                                    }
                                    pageing.style.width = 455 - (5 - scope.dataPageCount + 1) * 36 + 'px';
                                    // 总页数大于最大显示页数时
                                } else if (scope.dataPageCount > scope.pageNumberListLength) {
                                    // 页数小于
                                    if (page == '...') {
                                        if (scope.pageNumberList[2] > scope.dataPageCount - 5) {
                                            scope.pageNumberList = [scope.dataPageCount - 4, scope.dataPageCount - 3, scope.dataPageCount - 2, scope.dataPageCount - 1, scope.dataPageCount];
                                            pageing.style.width = "419px";
                                            return
                                        }
                                        pageing.style.width = "455px";
                                        scope.pageNumberList = [scope.pageNumberList[2] + 1, scope.pageNumberList[2] + 2, scope.pageNumberList[2] + 3, '...', scope.dataPageCount - 1, scope.dataPageCount];
                                        return
                                    } else if (page == 1) {
                                        pageing.style.width = "455px";
                                        scope.pageNumberList = [page, page + 1, page + 2, '...', scope.dataPageCount - 1, scope.dataPageCount];
                                        return
                                    } else if (page == scope.dataPageCount - 2 && scope.pageNumberList.indexOf(page) < 0) {
                                        scope.pageNumberList = [scope.dataPageCount - 4, scope.dataPageCount - 3, scope.dataPageCount - 2, scope.dataPageCount - 1, scope.dataPageCount];
                                    } else if (page == scope.dataPageCount || page > scope.dataPageCount - 5) {
                                        return
                                    } else if (scope.pageNumberList.indexOf(page) < 0) {
                                        pageing.style.width = "455px";
                                        if (page > scope.pageNumberList[2] && page < scope.dataPageCount - 5) {
                                            scope.pageNumberList = [page, page + 1, page + 2, '...', scope.dataPageCount - 1, scope.dataPageCount];
                                        } else if (page > scope.pageNumberList[2] && page > scope.dataPageCount - 5) {
                                            scope.pageNumberList = [scope.dataPageCount - 4, scope.dataPageCount - 3, scope.dataPageCount - 2, scope.dataPageCount - 1, scope.dataPageCount];
                                            pageing.style.width = "419px";
                                            return
                                        } else if (page < scope.pageNumberList[0]) {
                                            scope.pageNumberList = [page, page + 1, page + 2, '...', scope.dataPageCount - 1, scope.dataPageCount];
                                        }
                                    }

                                }
                            }else{
                                scope.conf.isShow = false;
                                scope.conf.isKong=true;
                            }
                        }

                    })
                };
                scope.conf.change = scope.changePage;
                scope.changePage(null, scope.dataStartPage);
            }

        }
    })
});